package com.ljx.itbbs.server.article.event.handler;

import com.ljx.itbbs.server.article.domain.enums.LikeEnum;
import com.ljx.itbbs.server.article.event.LikeEvent;
import com.ljx.itbbs.server.article.service.ArticleService;
import com.ljx.itbbs.server.article.service.CommentService;
import com.ljx.itbbs.server.article.service.LikeRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-03-27  19:34
 */
@Component
public class LikeArticleEventHandler {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private LikeRecordService likeRecordService;

    @Autowired
    private CommentService commentService;

    /**
     * 更新点赞
     * @param event
     */
    @Async
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = LikeEvent.class, fallbackExecution = true)
    public void increaseLikeNum(LikeEvent event) {
        if (event.getType().equals(LikeEnum.ARTICLE.getType())){
            articleService.increaseLikeNum(event.getObjId());
        } else if(event.getType().equals(LikeEnum.COMMENT.getType())){
            commentService.increaseLikeNum(event.getObjId(), event.getCommentType());
        }
    }

    /**
     * 保存记录
     * @param event
     */
    @Async
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = LikeEvent.class, fallbackExecution = true)
    public void saveLikeRecord(LikeEvent event) {
        likeRecordService.saveLikeRecord(event.getObjKey(), event.getUserId(), event.getType());
    }
}
